package com.uzai.console.web.user;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.google.common.collect.ImmutableMap;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.AccDetailTypeEnum;
import com.uzai.common.enums.IdentityEnum;
import com.uzai.common.enums.UserBlackTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.annotation.SystemLogType;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.dto.TbUserInfo.TbUserInfoIdDto;
import com.uzai.console.dto.TbUserInfo.TbUserInfoQuery;
import com.uzai.console.dto.TbUserInfo.TbUserInfoUpdateDto;
import com.uzai.console.dto.user.UserUpdateMarketingTagDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoIdDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.dto.profit.ladderratiogroup.LadderRatioGroupQuery;
import com.uzai.console.dto.profit.prirewardrule.PriRewardRuleQuery;
import com.uzai.console.dto.user.usertype.UserTypeQuery;
import com.uzai.console.dto.user.wechatuser.*;
import com.uzai.console.dto.user.useraccdetail.UserAccDetailQuery;
import com.uzai.console.dto.wxpubmanage.WxpubInfoListQuery;
import com.uzai.console.entity.*;
import com.uzai.console.entity.wxpubmanage.WxpubInfoEntity;
import com.uzai.console.enums.FriendRequestScene;
import com.uzai.console.enums.SmsType;
import com.uzai.console.enums.SystemModelEnum;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.user.WechatUserBatchService;
import com.uzai.console.service.user.WechatUserGroupSendMsgService;
import com.uzai.console.service.user.WechatUserService;
import com.uzai.console.service.user.WechatUserSyncService;
import com.uzai.console.vo.base.SelectIdVo;
import com.uzai.console.vo.base.SelectKeyVo;
import com.uzai.console.vo.cpa.CpaSelectVo;
import com.uzai.console.vo.tbuserinfo.TbUserInfoVo;
import com.uzai.console.vo.user.usertype.UserTypeInfoVo;
import com.uzai.console.vo.user.wechatuser.*;
import com.uzai.console.vo.user.useraccdetail.UserAccDetailInfoVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author liuqi
 * @date 2021年08月25日 20:15
 */
@Api(value = "个人微信用户",tags = "用户管理|个人微信用户")
@ApiSort(15)
@RestController
public class WechatUserContoller extends BaseController {
    private Logger logger = LoggerFactory.getLogger(WechatUserContoller.class);

    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private WechatUserSyncService wechatUserSyncService;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private PriRewardRuleMapper priRewardRuleMapper;
    @Autowired
    private LadderRatioGroupMapper ladderRatioGroupMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private WechatUserGroupSendMsgService wechatUserGroupSendMsgService;
    @Autowired
    private WechatUserBatchService wechatUserBatchService;
    @Autowired
    private WxpubInfoMapper wxpubInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    @ApiOperation(value = "分页查询微信用户列表", notes = "分页查询微信用户列表", response = WechatUserPageVo.class)
    @ApiOperationSupport(order = 1)
    @PostMapping("/wechatuser/findWechatUserList")
    public Object findWechatUserList(@RequestBody WechatUserQuery wechatUserQuery){
        return wechatUserService.findWechatUserList(wechatUserQuery);
    }

    @ApiOperation(value = "查询微信用户详情", notes = "查询微信用户详情", response = WechatUserInfoVo.class)
    @ApiOperationSupport(order = 2)
    @PostMapping("/wechatuser/findWechatUserInfo")
    public Object findWechatUserInfo(@RequestBody WechatUserIdDto wechatUserIdDto){
        return wechatUserService.findWechatUserInfo(wechatUserIdDto);
    }

    @ApiOperation(value = "查询会员身份下拉列表", notes = "查询会员身份下拉列表", response = SelectKeyVo.class)
    @ApiOperationSupport(order = 3)
    @PostMapping("/wechatuser/findIdentityListSelect")
    public Object findIdentityListSelect(){
        List<SelectKeyVo> selectKeyVoList = new ArrayList<>();
        IdentityEnum[] IdentityEnumArr = IdentityEnum.values();
        if(IdentityEnumArr != null && IdentityEnumArr.length > 0){
            for(IdentityEnum identityEnum : IdentityEnumArr){
                SelectKeyVo selectKeyVo =  new SelectKeyVo();
                //页面显示 身份
                selectKeyVo.setKey(String.valueOf(identityEnum.getId()));
                selectKeyVo.setValue(identityEnum.getDesc());
                selectKeyVoList.add(selectKeyVo);
            }
        }
        return selectKeyVoList;
    }


    @ApiOperation(value = "查询会员类型", notes = "查询会员类型", response = SelectIdVo.class)
    @ApiOperationSupport(order = 3)
    @PostMapping("/wechatuser/findUserTypeList")
    public Object findUserTypeList(@RequestBody UserTypeQuery userTypeQuery){
        List<SelectIdVo> selectIdVoList = new ArrayList<>();
        List<UserType> userTypeList = userTypeMapper.findByList(userTypeQuery);
        if(userTypeList != null && userTypeList.size() > 0){
            for(UserType userType : userTypeList){
                SelectIdVo selectIdVo =  new SelectIdVo();
                selectIdVo.setKey(userType.getId());
                //页面显示 身份-类型名称
                UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userType.getGroupId(), userType.getMerId());
                if(userTypeGroup == null){
                    userTypeGroup = new UserTypeGroup();
                }
                selectIdVo.setValue(Tools.getStr(userTypeGroup.getName())  + "-" + userType.getName() + "（"  + IdentityEnum.getById(userType.getIdentity()).getDesc() + "）");
                //是否默认
                selectIdVo.setIsDefault(userType.getIsDefault());
                selectIdVoList.add(selectIdVo);
            }
        }
        return selectIdVoList;
    }

    @ApiOperation(value = "查询结果添加群发任务", notes = "查询结果添加群发任务")
    @ApiOperationSupport(order = 4)
    @PostMapping("/wechatuser/sendMessageToUserSelected")
    public Object sendMessageToUserSelected(@RequestBody WechatUserBatchSendMsgDto wechatUserBatchSendMsgDto){
        wechatUserGroupSendMsgService.groupSendMsg(wechatUserBatchSendMsgDto);
        return true;
    }

    @ApiOperation(value = "添加群发任务（多选框选择会员）", notes = "查询结果添加群发任务（多选框选择会员）")
    @ApiOperationSupport(order = 4)
    @PostMapping("/wechatuser/sendMessageToUserBatch")
    public Object sendMessageToUserBatch(@RequestBody WechatUserSendMsgBatchDto wechatUserSendMsgBatchDto){
        wechatUserGroupSendMsgService.groupSendMsgBatch(wechatUserSendMsgBatchDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "删除所查询的会员数据", notes = "删除所查询的会员数据")
    @ApiOperationSupport(order = 5)
    @PostMapping("/wechatuser/deleteUserSelected")
    public Object deleteUserSelected(@RequestBody WechatUserBatchDeleteDto wechatUserBatchDeleteDto){
        wechatUserSyncService.deleteUserSelected(wechatUserBatchDeleteDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "批量删除会员数据（多选框）", notes = "删除所查询的会员数据（多选框）")
    @ApiOperationSupport(order = 5)
    @PostMapping("/wechatuser/deleteUserBatch")
    public Object deleteUserBatch(@RequestBody WechatUserIdListDto wechatUserIdListDto){
        wechatUserSyncService.deleteUserBatch(wechatUserIdListDto);
        return true;
    }

    @ApiOperation(value = "查询定投项目下拉选择框列表", notes = "查询定投项目下拉选择框列表", response = CpaSelectVo.class)
    @ApiOperationSupport(order = 6)
    @PostMapping("/wechatuser/findCpcSelectList")
    public Object findCpcSelectList(){
        Long merId = getLoginInfo().getMerId();
        //通过merID查询定投项目
        List<CpaSelectVo> cpaSelectVoList =  new ArrayList<>();
        CpaSelectVo cpaSelectVo_1 = new CpaSelectVo();
        cpaSelectVo_1.setId(1L);
        cpaSelectVo_1.setName("定投项目一");
        cpaSelectVoList.add(cpaSelectVo_1);
        CpaSelectVo cpaSelectVo_2 = new CpaSelectVo();
        cpaSelectVo_2.setId(2L);
        cpaSelectVo_2.setName("定投项目二");
        cpaSelectVoList.add(cpaSelectVo_2);
        return cpaSelectVoList;
    }

    @ApiOperation(value = "查询结果定投筛选", notes = "查询结果定投筛选")
    @ApiOperationSupport(order = 7)
    @PostMapping("/wechatuser/optCpcToUserSelected")
    public Object optCpcToUserSelected(@RequestBody WechatUserBatchOptCpcDto wechatUserBatchOptCpcDto){
        wechatUserSyncService.optCpcToUserSelected(wechatUserBatchOptCpcDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "单个发送消息", notes = "单个发送消息")
    @ApiOperationSupport(order = 8)
    @PostMapping("/wechatuser/sendMessageToOneUser")
    public Object sendMessageToOneUser(@RequestBody WechatUserSendMsgDto wechatUserSendMsgDto){
        //单个用户发送消息，不需要添加标签和修改备注
        wechatUserService.sendMessageToOneUser(wechatUserSendMsgDto);
        return true;
    }

    @ApiOperation(value = "查询下级成员", notes = "查询下级成员",response = WechatUserPageVo.class)
    @ApiOperationSupport(order = 9)
    @PostMapping("/wechatuser/findSonUserList")
    public Object findSonUserList(@RequestBody FindSonUserListQuery findSonUserListQuery){
        return wechatUserService.findSonUserList(findSonUserListQuery);
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "删除用户", notes = "删除用户")
    @ApiOperationSupport(order = 10)
    @PostMapping("/wechatuser/deleteUserById")
    public Object deleteUserById(@RequestBody WechatUserIdDto wechatUserIdDto){
        //删除成功
        wechatUserService.deleteUserById(wechatUserIdDto.getId(), wechatUserIdDto.getMerId());
        return true;
    }

    @ApiOperation(value = "查询账户明细类型下拉列表框", notes = "查询账户明细类型下拉列表框", response = SelectIdVo.class)
    @ApiOperationSupport(order = 11)
    @PostMapping("/wechatuser/findWechatUserAccDetailTypeList")
    public Object findWechatUserAccDetailTypeList(){
        List<SelectIdVo> selectIdVoList = new ArrayList<>();
        for (AccDetailTypeEnum accDetailType : AccDetailTypeEnum.values()){
            SelectIdVo selectIdVo = new SelectIdVo();
            selectIdVo.setKey(Long.valueOf(accDetailType.getValue()));
            selectIdVo.setValue(accDetailType.getDesc());
            selectIdVoList.add(selectIdVo);
        }
        return selectIdVoList;
    }

    @ApiOperation(value = "查询账户明细列表", notes = "查询账户明细列表", response = UserAccDetailInfoVo.class)
    @ApiOperationSupport(order = 12)
    @PostMapping("/wechatuser/findWechatUserAccDetailList")
    public Object findWechatUserAccDetailList(@RequestBody UserAccDetailQuery wechatUserAccDetailQuery){
        return wechatUserService.findWechatUserAccDetailList(wechatUserAccDetailQuery);
    }

    @ApiOperation(value = "查询会员渠道ID列表", notes = "查询会员渠道ID列表", response = TbUserInfoVo.class)
    @ApiOperationSupport(order = 13)
    @PostMapping("/wechatuser/findTbUserInfoList")
    public Object findTbUserInfoList(@RequestBody TbUserInfoQuery tbUserInfoQuery){
        return wechatUserService.findTbUserInfoList(tbUserInfoQuery);
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改会员渠道ID", notes = "修改会员渠道ID")
    @ApiOperationSupport(order = 14)
    @PostMapping("/wechatuser/updateTbUserInfo")
    public Object updateTbUserInfo(@RequestBody TbUserInfoUpdateDto tbUserInfoUpdateDto){
        wechatUserService.updateTbUserInfo(tbUserInfoUpdateDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改余额积分", notes = "修改余额积分")
    @ApiOperationSupport(order = 15)
    @PostMapping("/wechatuser/updateWechatUserBalance")
    public Object updateWechatUserBalance(@RequestBody WechatUserUpdateBalanceDto wechatUserUpdateBalanceDto){
        wechatUserService.updateWechatUserBalance(wechatUserUpdateBalanceDto);
        return true;
    }

    @ApiOperation(value = "查询定向规则下拉列表框", notes = "查询定向规则下拉列表框", response = SelectIdVo.class)
    @ApiOperationSupport(order = 16)
    @PostMapping("/wechatuser/findPriRewardRuleList")
    public Object findPriRewardRuleList(){
        List<SelectIdVo> selectIdVoList = new ArrayList<>();
        PriRewardRuleQuery priRewardRuleQuery = new PriRewardRuleQuery();
        priRewardRuleQuery.setMerId(getLoginInfo().getMerId());
        List<PriRewardRule> priRewardRuleList = priRewardRuleMapper.findByList(priRewardRuleQuery);
        if(priRewardRuleList != null && priRewardRuleList.size() > 0){
            for(PriRewardRule priRewardRule : priRewardRuleList){
                SelectIdVo selectIdVo =  new SelectIdVo();
                selectIdVo.setKey(priRewardRule.getId());
                selectIdVo.setValue(priRewardRule.getName());
                selectIdVoList.add(selectIdVo);
            }
        }
        return selectIdVoList;
    }

    @ApiOperation(value = "查询阶梯规则组下拉列表框", notes = "查询阶梯规则组下拉列表框", response = SelectIdVo.class)
    @ApiOperationSupport(order = 17)
    @PostMapping("/wechatuser/findLadderRatioGroupList")
    public Object findLadderRatioGroupList(){
        List<SelectIdVo> selectIdVoList = new ArrayList<>();
        LadderRatioGroupQuery ladderRatioGrouQuery = new LadderRatioGroupQuery();
        ladderRatioGrouQuery.setMerId(getLoginInfo().getMerId());
        List<LadderRatioGroup> ladderRatioGroupList = ladderRatioGroupMapper.findByList(ladderRatioGrouQuery);
        if(ladderRatioGroupList != null && ladderRatioGroupList.size() > 0){
            for(LadderRatioGroup ladderRatioGroup : ladderRatioGroupList){
                SelectIdVo selectIdVo =  new SelectIdVo();
                selectIdVo.setKey(ladderRatioGroup.getId());
                selectIdVo.setValue(ladderRatioGroup.getName());
                selectIdVoList.add(selectIdVo);
            }
        }
        return selectIdVoList;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改定向比例", notes = "修改定向比例")
    @ApiOperationSupport(order = 18)
    @PostMapping("/wechatuser/updateWechatUserPriRewardRules")
    public Object updateWechatUserPriRewardRules(@RequestBody WechatUserUpdatePriRewardRulesDto wechatUserUpdatePriRewardRulesDto){
        wechatUserService.updateWechatUserPriRewardRules(wechatUserUpdatePriRewardRulesDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改个人微信用户会员标签", notes = "修改个人微信用户会员标签")
    @ApiOperationSupport(order = 18)
    @PostMapping("/wechatuser/updateSysTags")
    public Object updateSysTags(@RequestBody UserUpdateMarketingTagDto userUpdateMarketingTagDto){
        wechatUserService.updateSysTags(userUpdateMarketingTagDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.ADD)
    @ApiOperation(value = "加入黑名单", notes = "加入黑名单")
    @ApiOperationSupport(order = 19)
    @PostMapping("/wechatuser/addBlackUser")
    public Object addBlackUser(@RequestBody WechatUserAddBlackDto wechatUserAddBlackDto){
        wechatUserService.addBlackUser(wechatUserAddBlackDto);
        return true;
    }

    @ApiOperation(value = "查询黑名单类型下拉列表框列表", notes = "查询黑名单类型下拉列表框列表", response = SelectIdVo.class)
    @ApiOperationSupport(order = 20)
    @PostMapping("/wechatuser/findUserBlackTypeList")
    public Object findUserBlackTypeList(){
        List<SelectIdVo> selectIdVoList = new ArrayList<>();

        UserBlackTypeEnum[] userBlackTypeArr = UserBlackTypeEnum.values();

        if(userBlackTypeArr != null  && userBlackTypeArr.length > 0){
            for(UserBlackTypeEnum userBlackType : userBlackTypeArr){
                SelectIdVo selectIdVo =  new SelectIdVo();
                selectIdVo.setKey(Long.valueOf(userBlackType.getValue()));
                selectIdVo.setValue(userBlackType.getDesc());
                selectIdVoList.add(selectIdVo);
            }
        }
        return selectIdVoList;
    }

    @ApiOperation(value = "查询余额总和", notes = "查询余额总和", response = WechatUserTotalVo.class)
    @ApiOperationSupport(order = 21)
    @PostMapping("/wechatuser/findWechatUserBalanceTotal")
    public Object findWechatUserBalanceTotal(@RequestBody WechatUserQuery wechatUserQuery){
        return  wechatUserMapper.findTotalBalance(wechatUserQuery);
    }

    @ApiOperation(value = "查询用户定向规则详情", notes = "查询用户定向规则详情", response = WechatUserPriRewardRulesVo.class)
    @ApiOperationSupport(order = 22)
    @PostMapping("/wechatuser/findWechatUserPriRewardRules")
    public Object findWechatUserPriRewardRules(@RequestBody WechatUserIdDto wechatUserIdDto){
        if(wechatUserIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询页面用户
        WechatUser wechatUser =  wechatUserMapper.selectById(wechatUserIdDto.getId(), wechatUserIdDto.getMerId());

        if(wechatUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }
        WechatUserPriRewardRulesVo wechatUserPriRewardRulesVo = new WechatUserPriRewardRulesVo();
        if(StringUtils.isNotBlank(wechatUser.getPriRewardRules())){
            wechatUserPriRewardRulesVo = JSONObject.parseObject(wechatUser.getPriRewardRules(), WechatUserPriRewardRulesVo.class);
        }

        wechatUserPriRewardRulesVo.setId(wechatUser.getId());
        wechatUserPriRewardRulesVo.setPriRewardRules(wechatUser.getPriRewardRules());

        return  wechatUserPriRewardRulesVo;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改微信用户详情", notes = "修改微信用户详情")
    @ApiOperationSupport(order = 23)
    @PostMapping("/wechatuser/updateWechatUser")
    public Object updateWechatUser(@RequestBody WechatUserInfoUpdateDto wechatUserInfoUpdateDto){
        wechatUserService.updateWechatUserInfo(wechatUserInfoUpdateDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "删除会员/渠道ID", notes = "删除会员/渠道ID")
    @ApiOperationSupport(order = 24)
    @PostMapping("/wechatuser/deleteTbUserInfo")
    public Object deleteTbUserInfo(@RequestBody TbUserInfoIdDto tbUserInfoIdDto){
        wechatUserService.deleteTbUserInfo(tbUserInfoIdDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "删除下级成员", notes = "删除下级成员")
    @ApiOperationSupport(order = 25)
    @PostMapping("/wechatuser/deleteSonWechatUser")
    public Object deleteSonWechatUser(@RequestBody WechatUserDeleteSonDto wechatUserDeleteSonDto){
        wechatUserService.deleteSonWechatUser(wechatUserDeleteSonDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "批量删除下级成员", notes = "批量删除下级成员")
    @ApiOperationSupport(order = 25)
    @PostMapping("/wechatuser/deleteSonWechatUserBatch")
    public Object deleteSonWechatUserBatch(@RequestBody WechatUserDeleteSonBatchDto wechatUserDeleteSonBatchDto){
        wechatUserSyncService.deleteSonWechatUserBatch(wechatUserDeleteSonBatchDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "查询结果批量修改", notes = "查询结果批量修改")
    @ApiOperationSupport(order = 27)
    @PostMapping("/wechatuser/batchUpdateToUserSelected")
    public Object batchUpdateToUserSelected(@RequestBody WechatUserBatchUpdateDto wechatUserBatchUpdateDto){

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.WECHAT_USERINFO_UPDATE_ORDER_OPE, wechatUserBatchUpdateDto.getMerId()));

        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"5分钟只允许一次请求");
        }

        //AOP切面，封装操作日志内容
        WechatUserQuery wechatUserQuery = wechatUserBatchUpdateDto.getWechatUserQuery();
        wechatUserQuery.setMerId(wechatUserBatchUpdateDto.getMerId());
        //查询总数
        Integer count = wechatUserMapper.findCount(wechatUserQuery);
        String aspectOperatorLog = "查询结果批量修改,修改数据共:"+count+"条";

        //判断是否修改了会员余额和积分
        Long merId = wechatUserBatchUpdateDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }
        boolean updateUserBalanceAndIntegralFlag = false;

        WechatUserUpdateDto wechatUserUpdateDto = wechatUserBatchUpdateDto.getWechatUserUpdateDto();
        if(wechatUserUpdateDto.getBalance() != null && wechatUserUpdateDto.getBalanceType() != null){
            //修改了余额
            updateUserBalanceAndIntegralFlag = true;
            if(Tools.getInteger(wechatUserUpdateDto.getBalanceType()).intValue() == 0){
                aspectOperatorLog = aspectOperatorLog + "；修改余额:" + wechatUserUpdateDto.getBalance();
            }else if(Tools.getInteger(wechatUserUpdateDto.getBalanceType()).intValue() == -1){
                aspectOperatorLog = aspectOperatorLog + "；减少余额:" + wechatUserUpdateDto.getBalance();
            }else if(Tools.getInteger(wechatUserUpdateDto.getBalanceType()).intValue() == 1){
                aspectOperatorLog = aspectOperatorLog + "；增加余额:" + wechatUserUpdateDto.getBalance();
            }
        }

        if(wechatUserUpdateDto.getIntegral() != null && wechatUserUpdateDto.getIntegralType() != null){
            //修改了积分
            updateUserBalanceAndIntegralFlag = true;
            if(Tools.getInteger(wechatUserUpdateDto.getIntegralType()).intValue() == 0){
                aspectOperatorLog = aspectOperatorLog + "；修改积分:" + wechatUserUpdateDto.getIntegral();
            }else if(Tools.getInteger(wechatUserUpdateDto.getIntegralType()).intValue() == -1){
                aspectOperatorLog = aspectOperatorLog + "；减少积分:" + wechatUserUpdateDto.getIntegral();
            }else if(Tools.getInteger(wechatUserUpdateDto.getIntegralType()).intValue() == 1){
                aspectOperatorLog = aspectOperatorLog + "；增加积分:" + wechatUserUpdateDto.getIntegral();
            }
        }

        //修改了余额积分，需要发送短信验证
        if(updateUserBalanceAndIntegralFlag){
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserBatchUpdateDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.UPDATE_USER_BALANCE_INTEGRAL.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(wechatUserBatchUpdateDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserBatchUpdateDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.UPDATE_USER_BALANCE_INTEGRAL.getDesc(), merchant.getMobile()));
            }
        }
        //AOP切面，封装操作日志内容
        wechatUserBatchUpdateDto.setAspectOperatorLog(aspectOperatorLog);

        wechatUserSyncService.batchUpdateToUserSelected(wechatUserBatchUpdateDto);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.WECHAT_USERINFO_UPDATE_ORDER_OPE, wechatUserBatchUpdateDto.getMerId()),wechatUserBatchUpdateDto.getMerId()+"",5, TimeUnit.MINUTES);

        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "批量修改会员信息（多选框选择会员）", notes = "批量修改会员信息（多选框选择会员）")
    @ApiOperationSupport(order = 27)
    @PostMapping("/wechatuser/batchUpdateToUserBatch")
    public Object batchUpdateToUserBatch(@RequestBody WechatUserUpdateBatchDto wechatUserUpdateBatchDto){

        //AOP切面，封装操作日志内容
        List<Long> idList = wechatUserUpdateBatchDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"请选择修改的会员");
        }
        String aspectOperatorLog = "批量修改会员信息(多选框),修改数据共:"+idList.size()+"条";

        //判断是否修改了会员余额和积分
        Long merId = wechatUserUpdateBatchDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }
        boolean updateUserBalanceAndIntegralFlag = false;

        WechatUserUpdateDto wechatUserUpdateDto = wechatUserUpdateBatchDto.getWechatUserUpdateDto();
        if(wechatUserUpdateDto.getBalance() != null && wechatUserUpdateDto.getBalanceType() != null){
            //修改了余额
            updateUserBalanceAndIntegralFlag = true;
            if(Tools.getInteger(wechatUserUpdateDto.getBalanceType()).intValue() == 0){
                aspectOperatorLog = aspectOperatorLog + ";修改余额：" + wechatUserUpdateDto.getBalance();
            }else if(Tools.getInteger(wechatUserUpdateDto.getBalanceType()).intValue() == -1){
                aspectOperatorLog = aspectOperatorLog + ";减少余额：" + wechatUserUpdateDto.getBalance();
            }else if(Tools.getInteger(wechatUserUpdateDto.getBalanceType()).intValue() == 1){
                aspectOperatorLog = aspectOperatorLog + ";增加余额：" + wechatUserUpdateDto.getBalance();
            }
        }

        if(wechatUserUpdateDto.getIntegral() != null && wechatUserUpdateDto.getIntegralType() != null){
            //修改了积分
            updateUserBalanceAndIntegralFlag = true;
            if(Tools.getInteger(wechatUserUpdateDto.getIntegralType()).intValue() == 0){
                aspectOperatorLog = aspectOperatorLog + ";修改积分：" + wechatUserUpdateDto.getIntegral();
            }else if(Tools.getInteger(wechatUserUpdateDto.getIntegralType()).intValue() == -1){
                aspectOperatorLog = aspectOperatorLog + ";减少积分：" + wechatUserUpdateDto.getIntegral();
            }else if(Tools.getInteger(wechatUserUpdateDto.getIntegralType()).intValue() == 1){
                aspectOperatorLog = aspectOperatorLog + ";增加积分：" + wechatUserUpdateDto.getIntegral();
            }
        }

        //修改了余额积分，需要发送短信验证
        if(updateUserBalanceAndIntegralFlag){
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserUpdateBatchDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.UPDATE_USER_BALANCE_INTEGRAL.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(wechatUserUpdateBatchDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserUpdateBatchDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.UPDATE_USER_BALANCE_INTEGRAL.getDesc(), merchant.getMobile()));
            }
        }
        //AOP切面，封装操作日志内容
        wechatUserUpdateBatchDto.setAspectOperatorLog(aspectOperatorLog);

        wechatUserSyncService.batchUpdateToUserBatch(wechatUserUpdateBatchDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "更新微信信息", notes = "更新微信信息", response = WechatUserInfoVo.class)
    @ApiOperationSupport(order = 28)
    @PostMapping("/wechatuser/updateUserInfoFromWechat")
    public Object updateUserInfoFromWechat(@RequestBody WechatUserIdDto wechatUserIdDto){
        return wechatUserService.updateUserInfoFromWechat(wechatUserIdDto);
    }

    @ApiOperation(value = "查询机器人下拉列表框列表", notes = "查询机器人下拉列表框列表", response = WechatUserDeciceInfoVo.class)
    @ApiOperationSupport(order = 29)
    @PostMapping("/wechatuser/findDeviceList")
    public Object findDeviceList(){
        List<WechatUserDeciceInfoVo> wechatUserDeciceInfoVoList = new ArrayList<WechatUserDeciceInfoVo>();
        DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
        deviceWechatInfoQuery.setMerId(getLoginInfo().getMerId());
        List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
        if(deviceWechatInfoList != null){
            for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList){
                WechatUserDeciceInfoVo wechatUserDeciceInfoVo = new WechatUserDeciceInfoVo();
                BeanUtils.copyProperties(deviceWechatInfo, wechatUserDeciceInfoVo);
                wechatUserDeciceInfoVoList.add(wechatUserDeciceInfoVo);
            }
        }
        return wechatUserDeciceInfoVoList;
    }

    @ApiOperation(value = "根据机器人id查询会员类型列表", notes = "根据机器人id查询会员类型列表", response = UserTypeInfoVo.class)
    @ApiOperationSupport(order = 30)
    @PostMapping("/wechatuser/findUserTypeListByDeviceUniqueId")
    public Object findUserTypeListByDeviceUniqueId(@RequestBody WechatUserDeviceUniqueIdDto wechatUserDeviceUniqueIdDto){
        return wechatUserBatchService.findUserTypeListByDeviceUniqueId(wechatUserDeviceUniqueIdDto);
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "批量修改默认客户端", notes = "批量修改默认客户端")
    @ApiOperationSupport(order = 31)
    @PostMapping("/wechatuser/updateDefaultClient")
    public Object updateDefaultClient(@RequestBody BatchUpdateDefaultClientDto batchUpdateDefaultClientDto){
        wechatUserBatchService.updateDefaultClient(batchUpdateDefaultClientDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "单个会员修改默认客户端", notes = "单个会员修改默认客户端")
    @ApiOperationSupport(order = 31)
    @PostMapping("/wechatuser/updateDefaultClientPersonal")
    public Object updateDefaultClientPersonal(@RequestBody UpdateDefaultClientPersonalDto updateDefaultClientPersonalDto){
        wechatUserBatchService.updateDefaultClientPersonal(updateDefaultClientPersonalDto);
        return true;
    }

    @ApiOperation(value = "查询同类型组的公众号机器人下拉列表框列表（过滤不是同类型组的机器人）", notes = "查询同类型组的公众号机器人下拉列表框列表（过滤不是同类型组的机器人）", response = WxpubInfoEntity.class)
    @ApiOperationSupport(order = 33)
    @PostMapping("/wechatuser/findSameGroupWxpubDeviceList")
    public Object findSameGroupWxpubDeviceList(@RequestBody WxpubDeviceUniqueIdDto wxpubDeviceUniqueIdDto){
        List<WxpubInfoEntity> wxpubInfoEntityList_vo = new ArrayList<>();
        if(wxpubDeviceUniqueIdDto.getWxpubDeviceUniqueId() != null){
            WxpubInfoEntity wxpubInfoEntity_self = wxpubInfoMapper.queryObject(wxpubDeviceUniqueIdDto.getWxpubDeviceUniqueId());
            if(wxpubInfoEntity_self != null){
                ConfigPlan configPlan_self = configPlanMapper.selectById(wxpubInfoEntity_self.getConfigId(), wxpubInfoEntity_self.getMerId());
                if(configPlan_self != null){
                    Long userTypeGroupId_self = configPlan_self.getUserTypeGroupId();
                    if(userTypeGroupId_self != null){
                        WxpubInfoListQuery wxpubInfoListQuery = new WxpubInfoListQuery();
                        wxpubInfoListQuery.setMerId(getLoginInfo().getMerId());
                        List<WxpubInfoEntity> wxpubInfoEntityList = wxpubInfoMapper.queryList(wxpubInfoListQuery);
                        if(wxpubInfoEntityList != null){
                            for (WxpubInfoEntity wxpubInfoEntity : wxpubInfoEntityList){
                                ConfigPlan configPlan = configPlanMapper.selectById(wxpubInfoEntity.getConfigId(), wxpubInfoEntity.getMerId());
                                //同一个会员类型组的机器人才能查询出来
                                if(configPlan != null && Tools.getLong(configPlan.getUserTypeGroupId()).longValue() == userTypeGroupId_self.longValue()){
                                    wxpubInfoEntityList_vo.add(wxpubInfoEntity);
                                }
                            }
                        }
                    }
                }
            }
        }
        return wxpubInfoEntityList_vo;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改互通的的公众号会员所在的公众号", notes = "修改互通的的公众号会员所在的公众号", response = Boolean.class)
    @ApiOperationSupport(order = 33)
    @PostMapping("/wechatuser/updateInterflowWxpubUser")
    public Object updateInterflowWxpubUser(@RequestBody UpdateWxpubUserDto updateWxpubUserDto){
        wechatUserService.updateInterflowWxpubUser(updateWxpubUserDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "解除会员互通信息", notes = "解除会员互通信息", response = Boolean.class)
    @ApiOperationSupport(order = 33)
    @PostMapping("/wechatuser/cleanUserUnionId")
    public Object cleanUserUnionId(@RequestBody CleanUserUnionIdDto cleanUserUnionIdDto){
        wechatUserService.cleanUserUnionId(cleanUserUnionIdDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改会员订阅消息", notes = "修改会员订阅消息")
    @ApiOperationSupport(order = 34)
    @PostMapping("/wechatuser/updateSubscribeInfo")
    public Object updateSubscribeInfo(@RequestBody UpdateSubscribeInfoDto updateSubscribeInfoDto){
        wechatUserService.updateSubscribeInfo(updateSubscribeInfoDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改会员营销奖励", notes = "修改会员营销奖励")
    @ApiOperationSupport(order = 35)
    @PostMapping("/wechatuser/updateMarketingReward")
    public Object updateMarketingReward(@RequestBody UpdateMarketingRewardDto updateMarketingRewardDto){
        wechatUserService.updateMarketingReward(updateMarketingRewardDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.WechatUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "个人微信会员查询结果批量修改营销策略", notes = "个人微信会员查询结果批量修改营销策略")
    @ApiOperationSupport(order = 36)
    @PostMapping("/wechatuser/updateMarketingRewardByQueryResult")
    public Object updateMarketingRewardByQueryResult(@RequestBody WechatUserUpdateMarketingRewardByQueryResultDto wechatUserUpdateMarketingRewardByQueryResultDto){

        Long merId = wechatUserUpdateMarketingRewardByQueryResultDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserUpdateMarketingRewardByQueryResultDto.getCode())){
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }
            //验证码是否正确
            if (!codeByRedis.equals(wechatUserUpdateMarketingRewardByQueryResultDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserUpdateMarketingRewardByQueryResultDto.getCode())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //验证成功，删除验证码
            redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
        }

        wechatUserSyncService.updateMarketingRewardByQueryResult(wechatUserUpdateMarketingRewardByQueryResultDto);
        return true;
    }

    @ApiOperation(value = "查询个人微信会员注册来源下拉列表", notes = "查询个人微信会员注册来源下拉列表", response = SelectKeyVo.class)
    @PostMapping("/wechatuser/regChannel/select")
    public Object scenes() {
        List<Map<String, Object>> scenes = new ArrayList<>(5);

        FriendRequestScene[] friendRequestScenes = FriendRequestScene.values();
        if(friendRequestScenes != null){
            for (FriendRequestScene friendRequestScene : friendRequestScenes) {
                //排除未知
                //if(friendRequestScene.getValue().intValue() != FriendRequestScene.UN_KNOW.getValue().intValue()){
                    scenes.add(ImmutableMap.of("key", friendRequestScene.getValue(), "value", friendRequestScene.getLabel()));
                //}
            }
        }

        return scenes;
    }

}
